package com.ruoyi.framework.interceptor;

import com.ruoyi.common.utils.TenantContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 租户ID自动注入拦截器
 * 统一从header、get、post参数中获取tenantId并设置到TenantContext
 */
@Component
public class TenantContextInterceptor implements HandlerInterceptor {

    /**
     * 在请求处理前自动获取tenantId并设置到TenantContext
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器
     * @return 是否继续处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String tenantIdStr = request.getHeader("tenantId");
        if (tenantIdStr == null || tenantIdStr.isEmpty()) {
            tenantIdStr = request.getParameter("tenantId");
        }
        if (tenantIdStr != null && !tenantIdStr.isEmpty()) {
            try {
                TenantContext.setTenantId(Long.parseLong(tenantIdStr));
            } catch (NumberFormatException e) {
                // 可根据需要记录日志或抛出异常
            }
        }
        return true;
    }

    /**
     * 请求完成后清理TenantContext，防止线程复用导致数据串扰
     * @param request 请求对象
     * @param response 响应对象
     * @param handler 处理器
     * @param ex 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        TenantContext.clear();
    }
} 